<template>
  <div class="register-container">
    <!-- <a-card class="register-card" title="注册"> -->
    <div class="box-sty">
      <div class="register-card">
        <a-form :model="formState" name="register" :rules="rules" :label-col="labelCol" ref="formRef">
          <a-col :span="24">First Name</a-col>
          <a-form-item name="first_name">
            <a-input v-model:value="formState.first_name" style="height: 44px;" placeholder="Please enter first_name"/>
          </a-form-item>
          <a-col :span="24">Last Name</a-col>
          <a-form-item name="last_name">
            <a-input v-model:value="formState.last_name" style="height: 44px;" placeholder="Please enter last_name"/>
          </a-form-item>
          <a-col :span="24">Email</a-col>
          <a-form-item name="email">
            <a-input v-model:value="formState.email" placeholder="Please enter email" style="height: 44px;">
            </a-input>
          </a-form-item>
          <!-- <a-col :span="24">Email Code</a-col>
          <a-form-item>
            <a-input class="input-class" controls="false" v-model="formState.email_code" style="height: 44px;"
              placeholder="Please enter verification code" :maxlength="6">
              <template #suffix>
                <button :class="['send-btn', { disabled: isCounting }]" :disabled="isCounting"
                  @click.stop="sendVerificationCode">
                  {{ isCounting ? `${countdown}s` : "Obtain verification code" }}
                </button>
              </template>
            </a-input>
          </a-form-item> -->

          <!--是否有邀请码-->
          <div style="margin-bottom: 15px;font-size: 14px;color: #000000;">
            <a-checkbox v-model:checked="codeChecked" @change="checkboxChange">Invitation Code</a-checkbox>
          </div>
          <a-col :span="24" v-if="codeChecked">Invitation Code</a-col>
          <a-form-item v-if="codeChecked">
            <a-input v-model:value="formState.invitation_code" style="height: 44px;" />
          </a-form-item>

          <a-col :span="24">Password</a-col>
          <a-form-item name="password">
            <a-input-password v-model:value="formState.password" placeholder="Please enter password" style="height: 44px;"
              @input="validatePassword">
            </a-input-password>
          </a-form-item>
          <div class="password-dec">
              <CheckOutlined v-if="isPasswordValid" :style="{fontSize: '17px', color: '#67C23A'}"/>
            <span>At least 8 characters</span>
          </div>
          <div class="password-dec">
              <CheckOutlined v-if="isPasswordComplex" :style="{fontSize: '17px', color: '#67C23A'}"/>
            <span>Contains uppercase and lowercase letters</span>
          </div>

          <a-col :span="24">Confirm Password</a-col>
          <a-form-item name="passwordConfirm">
            <a-input-password v-model:value="formState.passwordConfirm" placeholder="Please enter confirm password" style="height: 44px;"
              @input="validatePasswordConfirm">
            </a-input-password>
          </a-form-item>
          <div class="password-dec">
              <CheckOutlined v-if="isPasswordConfirmed" :style="{fontSize: '17px', color: '#67C23A'}"/>
            The confirmation password must match the password
          </div>
          <!-- 手机号区号 -->
          <a-col :span="24">Contact Telephone</a-col>
          <a-form-item name="Contact Telephone">
            <PhoneNumberInput
                style="width: 100%"
                :initialPhoneNumber="phoneNumber"
                :initialCountryCode="countryCode"
                @update:phoneData="updatePhoneData"
            />
          </a-form-item>
          <!-- 谷歌人机验证 -->
          <vue-recaptcha :sitekey="siteKey" size="normal" theme="light" @verify="onVerify" @expire="recaptchaExpired"  @fail="recaptchaFailed"></vue-recaptcha>
          <!-- <div class="form-footer">
          <router-link to="/login">已有账号？立即登录</router-link>
        </div> -->
        </a-form>
      </div>
      <div class="submit-sty" @click="registerClick">CREATE AN ACCOUNT</div>
      <!-- <a-row>
        <a-col :span="24">Tick here to be the first to hear about all Reiss sale and promotional offers, including any
          other
          marketing.</a-col>
      </a-row>
      <a-checkbox v-model:checked="checked" style="margin: 10px 0px;">Email</a-checkbox>
      <a-row>
        <a-col :span="24">We would love to keep in touch by email with the latest information about Reiss
          including news of store and
          sale
          events. You can ask us to stop at any time using the unsubscribe link in all of our messages or by changing
          your
          preferences in 'My Account'. For more information, see our Privacy and Cookie Policy.</a-col>
      </a-row>
      <a-row :gutter="16" style="margin-top: 20px;">
        <a-col :span="15">
          By clicking 'Register My Account' you agree to the Terms and Conditions. To find out how we
          process
          your personal information, see our Privacy & Cookie Policy.</a-col>
        <a-col :span="9">
          <a-button type="primary" html-type="submit" block class="submit-sty" @click="registerClick">Register My Account</a-button>
        </a-col>
      </a-row> -->


    </div>
    <!-- </a-card> -->
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref,toRaw,watch,onUnmounted,onMounted } from 'vue';
import { UserOutlined, LockOutlined ,CheckOutlined} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useRouter,useRoute } from 'vue-router';
import type { Rule } from 'ant-design-vue/es/form';
import PhoneNumberInput from "@/components/PhoneNumberInput.vue"
// reCAPTCHA 组件
import VueRecaptcha from 'vue3-recaptcha2'
import { register } from '@/api/user'
import { Local } from "@/utils/storage.ts";
import { getSendCode,getSetting } from '@/api/index'

interface FormState {
  email: string;
  code: string;
  mobile: string;
  password: string;
  invitation_code: string;
  first_name: string;
  last_name: string;
  passwordConfirm: string
  g_recaptcha_response: string;
}
const labelCol = { style: { width: '150px' } };
const router = useRouter();
const route = useRoute();
const formRef = ref();
const formState = reactive<FormState>({
  email: '',
  code: '',
  password: '',
  first_name: '',
  last_name: '',
  passwordConfirm: '',
  g_recaptcha_response: '',
  mobile:'',
  invitation_code: '',//邀请码
});
watch(() => formState.mobile, (newValue) => {
  console.log('电话号码更新:', newValue);
  formState.mobile =newValue;
});

watch(() => formState.code, (newValue) => {
  console.log('国家区号更新:', newValue);
  formState.code =newValue;
});
// 在组件挂载时从URL获取邀请码
onMounted(() => {
  // 从URL中获取邀请码参数
  const codeFromUrl = route.query.code;
  
  if (codeFromUrl && typeof codeFromUrl === 'string') {
    // 自动勾选"我有邀请码"
    codeChecked.value = true;
    // 设置邀请码值
    formState.invitation_code = codeFromUrl;
    console.log('自动填写邀请码:', codeFromUrl);
  }
});
const rules: Record<string, Rule[]> = {
  first_name: [
    { required: true, message: 'Please enter first name', trigger: 'blur' },
  ],
  last_name: [
    { required: true, message: 'Please enter last name', trigger: 'blur' },
  ],
  password: [
    { required: true, message: 'Please enter password', trigger: 'blur' },
    { min: 8, message: 'Password does not meet requirements', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: 'The password consists of at least eight characters, including uppercase and lowercase letters as well as numbers',
      trigger: 'blur'
    }
  ],
  passwordConfirm: [
  { required: true, message: 'Please enter password', trigger: 'blur' },
    { min: 8, message: 'Password does not meet requirements', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: 'The password consists of at least eight characters, including uppercase and lowercase letters as well as numbers',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: 'Please enter email', trigger: 'blur' },
    { type: 'email', message: 'Please enter the correct email address', trigger: ['blur', 'change'] }
  ],
  email_code: [
    { required: true, message: 'Please enter email verification code', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: 'Please enter the correct email verification code', trigger: 'blur' }
  ],
};
// 区号手机号验证
// 处理手机号和国家代码
const phoneNumber = ref('');
const countryCode = ref('+1');
// 更新手机号数据
const updatePhoneData = (phoneData) => {
  if (phoneData) {
    // 即使手机号无效，也保存当前输入的值
    if (phoneData.isValid) {
      formState.mobile = phoneData.data.phoneNumber;
      formState.code = phoneData.data.countryCode;
      countryCode.value = phoneData.data.countryCode;
    } else {
      // 即使无效也保存当前输入的值，确保用户输入不会丢失
      formState.mobile = phoneData.data.phoneNumber;
      formState.code = phoneData.data.countryCode;
      countryCode.value = phoneData.data.countryCode;
    }
  }
};
//拿到网站密钥
// const siteKey = '6LflA-MqAAAAAChtyQ0Xsn337ycrybSGkHMEbPmw'
const siteKey = ref('')
//获取网站密钥
const getSiteKey = async () => {
  const res = await getSetting();
  if (res.code === 200) {
    siteKey.value = res.result.google_site_key;
    Local.set('settingConfig', res.result)
  }
}
if (!Local.get('settingConfig')) {
  getSiteKey();
} else {
  siteKey.value = Local.get('settingConfig').google_site_key
}

const isRecaptcha = ref(false)
//获取token发送到后端验证
const onVerify = (token: string) => {
  formState.g_recaptcha_response = token
    isRecaptcha.value = true
}
// 是否有邀请码
const inputDisplay = ref(false)
const codeChecked = ref(false)
const checkboxChange = () => {
  if (codeChecked.value) {
    inputDisplay.value = !inputDisplay.value;
  }
}
const isPasswordValid = ref(false)
const isPasswordComplex = ref(false)
const isPasswordConfirmed = ref(false)
const validatePassword = () => {
  isPasswordValid.value = formState.password.length >= 8;
  isPasswordComplex.value = /^(?=.*[a-z])(?=.*[A-Z]).*$/.test(formState.password);
}

const validatePasswordConfirm = () => {
  isPasswordConfirmed.value = formState.password === formState.passwordConfirm;
}
// 返回到登录页面
const goBack = () => {
  router.push('/login')
}
// 倒计时相关
const countdown = ref(0);
const isCounting = ref(false);
let timer: NodeJS.Timeout | null = null;

// 邮箱验证码发送
const sendVerificationCode = async (event: Event) => {
  event.preventDefault(); // 阻止默认行为
  
  if (!formState.email) {
    message.warning('Please enter email.');
    return;
  }

  try {
    // 开始倒计时
    isCounting.value = true;
    countdown.value = 60;
    
    // 清除之前的定时器
    if (timer) {
      clearInterval(timer);
    }

    // 设置新的定时器
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer!);
        isCounting.value = false;
      }
    }, 1000);

    const res = await getSendCode(formState.email);
    if (res.code === 200) {
      message.success("Verification code sent successfully");
    } else if (res.code === 40023) {
      message.warning(res.msg);
      // 发送失败时重置倒计时
      clearInterval(timer!);
      isCounting.value = false;
      countdown.value = 0;
    }
  } catch (error) {
    // 发生错误时重置倒计时
    if (timer) {
      clearInterval(timer);
    }
    isCounting.value = false;
    countdown.value = 0;
    message.error("Failed to send verification code");
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
// 注册
const registerClick = () => {
  formRef.value.validate().then(() => {
      register(formState).then((res) => {
        if (res.code == 200) {
          message.success('successfully registered')
          try {
            setTimeout(() => {
              router.push({
                path: '/login',
                query: { refresh: 1 }
              }).then(() => {
                window.location.reload()
              });
            }, 800);
            Local.set('ba-user-token', res.result.token);
            // 等待用户信息加载完成
            // userStore.setUserInfo();
            // mitt.emit('getCartList');
            // router.push({
            //   path: '/ShoppingListMain/MyAccount',
            //   query: { refresh: 1 }
            // })
          } catch (error) {
            message.error("Failed to load user info");
          }
          // 若注册成功跳转到登录界面
          // router.go(0)
        }
        formRef.value.resetFields()
      })
    })
    .catch(error => {
      console.log('error', error);
    });
};

</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}
.send-btn {
  background: #b38654;
  color: white;
  border: none;
  padding: 6px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: all 0.3s;
}

.send-btn.disabled {
  background: #ad9175;
  cursor: not-allowed;
}

.box-sty {
  width: 830px;
}

.register-card {
  width: 100%;
  max-width: 640px;
}

.form-footer {
  text-align: right;
  margin-top: 16px;
}

.desp-sty {
  /* padding-top: 16px; */
}

.submit-sty {
  background-color: #b38654 !important;
  width: 258px;
  padding: 14px 0px;
  color: #fff;
  font-weight: 700 !important;
  margin: 30px auto 0 auto;
  cursor: pointer;
  text-align: center;
}

.password-dec {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-page-header {
  box-sizing: border-box;
  margin: 0;
  padding: 5px 24px;
  color: rgba(0, 0, 0, 0.88);
  font-size: 12px;
  line-height: 1.5714285714285714;
  list-style: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  position: relative;
  background-color: #f7f7f7;
  text-align: center;
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-page-header .ant-page-header-heading-title {
  margin-right: 12px;
  margin-bottom: 0;
  color: rgba(0, 0, 0, 0.88);
  font-weight: 600;
  font-size: 12px !important;
  line-height: 32px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: center;
}

</style>